package com.ruoyi.youtian.service.impl;

import com.ruoyi.Gzmx_device.domain.Gzmx_device;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.gzmx_scdw.domain.Gzmx_scdw;
import com.ruoyi.gzmx_scdw.domain.Gzmx_scdwVo;
import com.ruoyi.gzmx_scdw.domain.ZtreeNew;
import com.ruoyi.youtian.domain.*;
import com.ruoyi.youtian.domain.vo.ScenePointVo;
import com.ruoyi.youtian.domain.vo.SourceTagVo;
import com.ruoyi.youtian.domain.vo.TSceneCategoryAssignEquipmentVo;
import com.ruoyi.youtian.mapper.TSceneCategoryMapper;
import com.ruoyi.youtian.mapper.ScenePointMapper;
import com.ruoyi.youtian.service.ITSceneCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 场景Service业务层处理
 *
 * @author ruoyi
 * @date 2022-09-12
 */
@Service
public class TSceneCategoryServiceImpl implements ITSceneCategoryService
{

    @Autowired
    private TSceneCategoryMapper tScenceCategoryMapper;

    @Autowired
    private ScenePointMapper scenePointMapper;


    /**
     * 查询场景
     *
     * @param sceneId 场景主键
     * @return 场景
     */
    @Override
    public TSceneCategory selectTSceneCategoryBySceneId(Long sceneId)
    {
        return tScenceCategoryMapper.selectTSceneCategoryBySceneId(sceneId);
    }

    /**
     * 查询场景列表
     *
     * @param tScenceCategory 场景
     * @return 场景
     */
    @DataScope(deptAlias = "d")
    @Override
    public List<TSceneCategory> selectTSceneCategoryList(TSceneCategory tScenceCategory)
    {
        return tScenceCategoryMapper.selectTSceneCategoryList(tScenceCategory);
    }

    /**
     * 新增场景
     *
     * @param tScenceCategory 场景
     * @return 结果
     */
    @Override
    public int insertTSceneCategory(TSceneCategory tScenceCategory)
    {
        tScenceCategory.setCreateTime(DateUtils.getNowDate());
        if(tScenceCategory.getParentId() != 0){
            TSceneCategory tSceneCategory = tScenceCategoryMapper.selectTSceneCategoryBySceneId(tScenceCategory.getParentId());
            tScenceCategory.setAncestors(tSceneCategory.getAncestors()+","+tScenceCategory.getParentId());
        }else {
            tScenceCategory.setAncestors("0");
        }
        return tScenceCategoryMapper.insertTSceneCategory(tScenceCategory);
    }

    /**
     * 修改场景
     *
     * @param tScenceCategory 场景
     * @return 结果
     */
    @Override
    public int updateTSceneCategory(TSceneCategory tScenceCategory)
    {
        tScenceCategory.setUpdateTime(DateUtils.getNowDate());
        return tScenceCategoryMapper.updateTSceneCategory(tScenceCategory);
    }

    /**
     * 删除场景信息
     * @param sceneId 场景主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteTSceneCategoryBySceneId(Long sceneId, String updateBy)
    {
        //删除场景与点位关联关系表
        tScenceCategoryMapper.deleteTScenePointBySceneId(sceneId);
        // 删除场景
        return tScenceCategoryMapper.deleteTSceneCategoryBySceneId(sceneId);
    }


    @Override
    public List<TSceneCategoryTreeSelect> selectTSceneCategoryTreeList(TSceneCategory tSceneCategory) {
        List<TSceneCategory> tSceneCategories = tScenceCategoryMapper.selectTSceneCategoryList(tSceneCategory);
        return buildTWorkspaceCategoryTreeSelect(tSceneCategories);
    }


    /**
     * 遍历所有
     * @param list
     * @return
     */
    @Override
    public List<TSceneCategoryTreeSelect> buildTWorkspaceCategoryTreeSelect(List<TSceneCategory> list) {
        // 遍历所有子节点
        List<TSceneCategory> tScenceCategoryList = buildTSceneCategoryTree(list);
        return tScenceCategoryList.stream().map(TSceneCategoryTreeSelect::new).collect(Collectors.toList());
    }


    @Override
    public List<TSceneCategoryTreeSelect> selectTSceneCategoryTreeList(TSceneCategory tSceneCategory, List<Gzmx_scdwVo> gzmx_scdwVoList) {

        List<TSceneCategory> tSceneCategories = tScenceCategoryMapper.selectTSceneCategoryList(tSceneCategory);
        return buildTWorkspaceCategoryTreeSelect2(tSceneCategories , gzmx_scdwVoList);
    }

    public List<ZtreeNew>  selectTSceneCategoryZtreeList(TSceneCategory tSceneCategory){
        List<TSceneCategory> tSceneCategoryList = tScenceCategoryMapper.selectTSceneCategoryList(tSceneCategory);
        List<ZtreeNew> ztreeNewList = new ArrayList<ZtreeNew>();
        if (tSceneCategoryList != null){
            for (TSceneCategory sceneCategory: tSceneCategoryList) {
                ZtreeNew ztreeNew = new ZtreeNew(sceneCategory);
                ztreeNewList.add(ztreeNew);
            }
        }
        return ztreeNewList;
    }

    @Override
    public List<TSceneCategoryTreeSelect> buildTWorkspaceCategoryTreeSelect2(List<TSceneCategory> list, List<Gzmx_scdwVo> gzmx_scdwVoList) {
        // 遍历所有子节点
        List<TSceneCategory> tScenceCategoryList = buildTSceneCategoryTree(list);

        List<TSceneCategory> sceneList = new ArrayList<TSceneCategory>();
        String labelType = "dept";
        //gzmx_scdwVoList
        for (Gzmx_scdwVo  vo : gzmx_scdwVoList) {
            TSceneCategory scene = new TSceneCategory();
            scene.setSceneId(vo.getId());
            scene.setSceneName(vo.getDwmc());
            scene.setParentId(vo.getFdwdm());
            scene.setLabelType(labelType);
            List<Gzmx_scdwVo> children = vo.getChildren();
            //  固定只能在二级单位下面添加
            // 找点位与工作区的关联 字段  sceneCategory.getEjdwId() = scdwVo.getId();
            List<TSceneCategory> sceneChildList = new ArrayList<TSceneCategory>();
            for (Gzmx_scdwVo scdwVo : children) {
                TSceneCategory tSceneCategory = new TSceneCategory();
                tSceneCategory.setSceneId(scdwVo.getId());
                tSceneCategory.setSceneName(scdwVo.getDwmc());
                tSceneCategory.setParentId(scdwVo.getParentId());
                List<TSceneCategory> tSceneCategoryList =  new ArrayList<TSceneCategory>();
                //  遍历场景集合查找其二级点位编号并放置树结构二级点位下
                for (TSceneCategory sceneCategory : tScenceCategoryList){
                    sceneCategory.setLabelType(labelType);
                    if(scdwVo.getId().intValue() == sceneCategory.getEjdwId()){
                        tSceneCategoryList.add(sceneCategory);
                    }
                }
                tSceneCategory.setChildren(tSceneCategoryList);
                sceneChildList.add(tSceneCategory);
            }
            scene.setChildren(sceneChildList);
            sceneList.add(scene);
        }
        return sceneList.stream().map(TSceneCategoryTreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public int assignEquipmentDel(TSceneCategoryAssignEquipmentVo scenceCategory) {
        // 为场景提供分配
        if(scenceCategory != null){
            int i = scenePointMapper.deleteTSceneScenePoint(scenceCategory);
            return i;
        }
        return 0;
    }

    @Override
    public List<Long> getChildTSceneCategoryIdList(long tSceneCategoryId) {
        List<Long> idList = new ArrayList<>();
        idList.add(tSceneCategoryId);
        List<TSceneCategory> tSceneCategories = this.selectTSceneCategoryList(null);
        List<TSceneCategory> list = buildTSceneCategoryTree(tSceneCategories);
        for (TSceneCategory tSceneCategory : list) {
            if(tSceneCategoryId == tSceneCategory.getSceneId()){
                idList.addAll(getChildSceneCateroyIdList(tSceneCategory.getChildren()));
            }
        }
        return idList;
    }




    @Override
    public List<ScenePointVo> selectScenePointVoListBySceneIdList(List<Long> sceneCategoryIdList, String pointName,String sceneName) {
        List<ScenePointVo> scenePointVoList = tScenceCategoryMapper.selectScenePointVoListBySceneIdList(sceneCategoryIdList, pointName, sceneName);
        for (ScenePointVo scenePointVo : scenePointVoList) {
            if(overLimt(scenePointVo.getValue(), scenePointVo.getUpperLimit(), scenePointVo.getLowerLimit())){
                scenePointVo.setDataState("异常");
            }else{
                scenePointVo.setDataState("正常");
            }
        }
        // 场景监测点的历史数据的值
        return scenePointVoList;
    }




    @Override
    public List<SourceTagVo> selectSourceTagHistoryListBySourceTag(SourceTagVo sourceTagVo) {
        List<SourceTagVo> sourceTagVoList = tScenceCategoryMapper.selectSourceTagHistoryListBySourceTag(sourceTagVo);
        return sourceTagVoList;
    }




    @Override
    public List<SourceTagVo> selectSourceTagListBySceneId(Long sceneId) {
        List<SourceTagVo> sourceTagVoList = tScenceCategoryMapper.selectSourceTagListBySceneId(sceneId);
        return sourceTagVoList;
    }

    private int countErrorData(int errorTagCount , List<SourceTagVo> sourceTagVoList){
        for (SourceTagVo tag : sourceTagVoList) {
            if(overLimt(tag.getValue(), tag.getUpperLimit(), tag.getLowerLimit())){
                errorTagCount++;
            }
        }
        return errorTagCount;
    }

    private boolean overLimt(long value,long upperLimit, long lowerLimit){
        if(value > upperLimit || value < lowerLimit  ){
            return true;
        }else {
            return false;
        }
    }


    @Override
    public List<TSceneCategory> getChildCategoryList(Long sceneId) {
        List<TSceneCategory> tSceneCategoryList = this.tScenceCategoryMapper.selectTSceneCategoryList(null);
        List<TSceneCategory> tSceneCategoryList1 = buildTSceneCategoryTree(tSceneCategoryList);
        List<TSceneCategory> childList = new ArrayList<TSceneCategory>();
        for (TSceneCategory tsceneCategory : tSceneCategoryList1) {
            if(tsceneCategory.getSceneId() == sceneId){
                if(tsceneCategory.getChildren() != null && tsceneCategory.getChildren().size()> 0){
                    findChild(childList, tsceneCategory.getChildren());
                }else{
                    childList.add(tsceneCategory);
                }
            }
        }
        return childList;
    }

    @Override
    public List<HashMap> getSceneCategoryMonitorListAll() {
        TSceneCategory sceneCategory = new TSceneCategory();
        sceneCategory.setParentId(0L);
        List<TSceneCategory> tSceneCategoryList = tScenceCategoryMapper.selectTSceneCategoryList(sceneCategory);
        List<HashMap> resultList = new ArrayList<>();
        for (TSceneCategory sc: tSceneCategoryList) {
            List<SourceTagVo> sourceTagVoList = tScenceCategoryMapper.selectSourceTagAllList(sc.getSceneId());
            HashMap<String, Object> hashMap = new HashMap<String, Object>();
            int errorTagCount = 0;
            hashMap.put("tagCount", sourceTagVoList.size());
            hashMap.put("errorTagCount",countErrorData(errorTagCount, sourceTagVoList));
            hashMap.put("sceneName",sc.getSceneName());
            resultList.add(hashMap);
        }
        return resultList;
    }

    @Override
    public List<HashMap> getSceneCategoryMonitorList(Long sceneId) {

        List<TSceneCategory> childCategoryList = getChildCategoryList(sceneId);
        List<HashMap> resultList = new ArrayList<>();
        for (TSceneCategory sc: childCategoryList) {
            List<SourceTagVo> sourceTagVoList = tScenceCategoryMapper.selectSourceTagListBySceneId(sc.getSceneId());
            HashMap<String, Object> hashMap = new HashMap<String, Object>();
            int errorTagCount = 0;
            hashMap.put("tagCount", sourceTagVoList.size());
            hashMap.put("errorTagCount",countErrorData(errorTagCount, sourceTagVoList));
            hashMap.put("sceneName",sc.getSceneName());
            resultList.add(hashMap);
        }
        return resultList;
    }



    /**
     * 场景管理左侧树
     * @param scdwSceneVo
     * @return
     */
    @Override
    public List<TreeSelect> selectScdwSceneTreeList(ScdwSceneVo scdwSceneVo,List<TreeSelect> scdwTreeList) {

        List<TSceneCategory> tSceneCategorieList = tScenceCategoryMapper.selectTSceneCategoryList(null);
        List<TSceneCategory> tScenceCategoryList = buildTSceneCategoryTree(tSceneCategorieList);
        List<TSceneCategoryTreeSelect> collect = tScenceCategoryList.stream().map(TSceneCategoryTreeSelect::new).collect(Collectors.toList());
        // 生产点位 场景树  点位
        List<TreeSelect> resultTreeSelect = scdwTreeList.stream().peek(s -> {
            recursionFnTree(s, collect, null);
        }).collect(Collectors.toList());

        return resultTreeSelect;
    }

    /**
     * 查询场景列表（功能修改）
     *
     * @param tScenceCategory 场景
     * @return 场景
     */
//    @DataScope(deptAlias = "d")
    @Override
    public List<TSceneCategory> selectTSceneCategoryreoList(TSceneCategory tScenceCategory)
    {
        return tScenceCategoryMapper.selectTSceneCategoryreoList(tScenceCategory);
    }

    /**
     *
     * @param treeSelect 生产点位
     * @param tScenceCategoryList 场景树
     * @param scenePointList 场景下面的节点
     */
    private void recursionFnTree(TreeSelect treeSelect, List<TSceneCategoryTreeSelect> tScenceCategoryList, List<ScenePoint> scenePointList)
    {
        if(treeSelect.getChildren() != null){
            // 得到子节点列表
            for ( TreeSelect tree: treeSelect.getChildren()) {
                if("5".equals(tree.getLevel())){
                    ArrayList<TreeSelect> childTreeDeviceList = new ArrayList<TreeSelect>();
                    for (TSceneCategoryTreeSelect sceneCategory : tScenceCategoryList) {
                        if((tree.getId()).equals(sceneCategory.getDw_5_id())){
                            TreeSelect treeSelect1 = new TreeSelect(sceneCategory);
                            //BeanUtils.copyProperties(sceneCategory,treeSelect1);

                            //TreeSelect
                            // 采集点位子集
                            ArrayList<TreeSelect>  childTreeTagList = new ArrayList<TreeSelect>();


                            //List<TSceneCategoryTreeSelect> children = sceneCategory.getChildren();

                            // TODO 遍历查找 场景点位关系表 将绑定的点位显示在场景结构下
                            // 遍历设备点位关系表 查找与该设备绑定的采集点位
//                          for (PointEquipment pointEquipment :  )  {
//                              // 上级 tree_id 为设备id
//                              if((treeSelect1.getId()).equals(pointEquipment.getEquipmentId())){
//                                  TreeSelect pointEquipmentTreeSelect = new TreeSelect(pointEquipment);
//                                  // 将添加进
//                                  childTreeTagList.add(pointEquipmentTreeSelect);
//                               }
//                           }
                            //treeSelect1.setChildren(childTreeTagList);
                            childTreeDeviceList.add(treeSelect1);
                        }
                    }
                    tree.setChildren(childTreeDeviceList);
                }
                recursionFnTree(tree , tScenceCategoryList, scenePointList);
            }
        }
    }

    /**
     *  查找当前节点下所有子节点列表
     * @param childList
     * @param list
     */
    private void findChild(List<TSceneCategory> childList, List<TSceneCategory> list){
        Iterator<TSceneCategory> iterator = list.iterator();
        while (iterator.hasNext()){
            TSceneCategory sc = iterator.next();
            if(sc.getChildren() != null &&  sc.getChildren().size() > 0){
                findChild(childList, sc.getChildren());
            }else{
                childList.add(sc);
            }
        }
    }

    private List<Long> getChildSceneCateroyIdList(List<TSceneCategory> list) {
        List<Long> resultList = new ArrayList<>();
        Iterator<TSceneCategory> iterator = list.iterator();
        while (iterator.hasNext()) {
            TSceneCategory tSceneCategory = iterator.next();
            resultList.add(tSceneCategory.getSceneId());
            if (tSceneCategory.getChildren().size() > 0) {
                getChildSceneCateroyIdList(tSceneCategory.getChildren());
            }
        }
        return resultList;
    }

    @Override
    public int assignEquipmentAdd(TSceneCategoryAssignEquipmentVo scenceCategory) {
        if(scenceCategory != null){
            List<ScenePoint> scenePointList = new ArrayList<ScenePoint>();
            List<String> equipmentIdList = scenceCategory.getPointIds();
            for (String equipmentId : equipmentIdList) {
                ScenePoint sceneEquipment = new ScenePoint();
                sceneEquipment.setCreateBy(scenceCategory.getCreateBy());
                sceneEquipment.setCreateTime(DateUtils.getNowDate());
                sceneEquipment.setSceneId(scenceCategory.getSceneId());
                sceneEquipment.setPointId(equipmentId);
                scenePointList.add(sceneEquipment);
            }
            int i = scenePointMapper.insertScenePointList(scenePointList);
            return i;
        }
        return 0;
    }

    @Override
    public List<TSceneCategory> buildTSceneCategoryTree(List<TSceneCategory> tSceneCategoryList) {
        List<TSceneCategory> returnList = new ArrayList<TSceneCategory>();
        List<Long>  tempList = new ArrayList<Long>();
        // 查询所有id
        for (TSceneCategory tSceneCategory: tSceneCategoryList ) {
            tempList.add(tSceneCategory.getSceneId());
        }
        for (TSceneCategory tSceneCategory : tSceneCategoryList ) {
            if (!tempList.contains(tSceneCategory.getParentId())){
                recursionFn(tSceneCategoryList, tSceneCategory);
                returnList.add(tSceneCategory);
            }
        }
        if (returnList.isEmpty()) {
            returnList = tSceneCategoryList;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<TSceneCategory> tSceneCategoryList, TSceneCategory sceneCategory)
    {
        // 得到子节点列表
        List<TSceneCategory> childList = getChildList(tSceneCategoryList, sceneCategory);
        sceneCategory.setChildren(childList);
        for (TSceneCategory tChild : childList)
        {
            if (hasChild(tSceneCategoryList, tChild))
            {
                recursionFn(tSceneCategoryList, tChild);
            }
        }
    }
    /**
     * 得到子节点列表
     */
    private List<TSceneCategory> getChildList(List<TSceneCategory> list, TSceneCategory tScenceCategory)
    {
        List<TSceneCategory> tlist = new ArrayList<TSceneCategory>();
        Iterator<TSceneCategory> it = list.iterator();
        while (it.hasNext())
        {
            TSceneCategory n = (TSceneCategory) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == tScenceCategory.getSceneId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<TSceneCategory> list, TSceneCategory t)
    {
        return getChildList(list, t).size() > 0;
    }


    /**
     * 查询场景列表
     *
     * @param tScenceCategory 场景
     * @return 场景
     */
    @DataScope(deptAlias = "d")
    @Override
    public List<TSceneCategory> selectTTTTSceneCategoryList(TSceneCategory tScenceCategory)
    {
        return tScenceCategoryMapper.selectTSceneCategoryreList(tScenceCategory);
    }


    @Override
    public List<ScenePointVo> selectScenePointVoListBySceneIdListreo(ScenePointVo scenePointVoe) {
        List<ScenePointVo> scenePointVoList = tScenceCategoryMapper.selectScenePointVoListBySceneIdListreo(scenePointVoe);
        for (ScenePointVo scenePointVo : scenePointVoList) {
            if(overLimt(scenePointVo.getValue(), scenePointVo.getUpperLimit(), scenePointVo.getLowerLimit())){
                scenePointVo.setDataState("异常");
            }else{
                scenePointVo.setDataState("正常");
            }
        }
        // 场景监测点的历史数据的值
        return scenePointVoList;
    }
}
